package com.lwh.easyExcel.util;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.lwh.easyExcel.controller.BdCheliangController;
import com.lwh.common.util.DateUtil;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelUtil {


	public static Map<String, Object> exportExcel(List<? extends BaseRowModel> list,String fileName,Class<? extends BaseRowModel> clazz) {
		ExcelWriter writer = null;
		OutputStream out = null;
		Map<String, Object> rsultMap = new HashMap<String, Object>();

		String dateStr = DateUtil.dateToString(new Date(), "yyyyMMddhhmmss");
		fileName = fileName + dateStr + ".xlsx";
		try {
			// 封装路径
			String filePath = BdCheliangController.class.getResource("").toURI().getPath();
			System.out.println(filePath);
			filePath = filePath.substring(0, filePath.lastIndexOf("/com")) + "/static/excel/" + fileName;

			File file = new File(filePath);
			if (!file.isFile()) {
				file.createNewFile();
			}
			out = new FileOutputStream(file);
			writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
			Sheet sheet = new Sheet(1, 0,clazz);
			sheet.setSheetName(fileName);
			writer.write(list, sheet);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
			rsultMap.put("success", false);
			return rsultMap;
		} finally {
			if (writer != null) {
				writer.finish();
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		rsultMap.put("success", true);
		rsultMap.put("url", fileName);
		return rsultMap;
	}
    
}
